package com.itheima.user.service.impl;

import com.itheima.user.dao.IUserDao;
import com.itheima.user.service.IUserService;
import com.itheima.domain.User;
import com.itheima.factory.Factory;

import java.io.IOException;
import java.util.ArrayList;

public class UserServiceImpl implements IUserService {
    private IUserDao iUserDao;

    {
        try {
            iUserDao = Factory.getIUserDao();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void addUser(User user) {
        iUserDao.addUser(user);
    }

    @Override
    public void deleteUser(String username) {
        iUserDao.deleteUser(username);
    }

    @Override
    public void updatePassword(String username, User user) {
        iUserDao.updatePassword(username, user);
    }

    @Override
    public ArrayList<User> findAllUser() {

        return iUserDao.findAllUser();
    }

    @Override
    public User findUser(String username) {
        ArrayList<User> list = iUserDao.findAllUser();
        for (User user : list) {
            if (user.getUsername().equals(username)) {
                return user;
            }
        }
        return null;
    }

    @Override
    public boolean isExists(String username) {
        ArrayList<User> list = iUserDao.findAllUser();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getUsername().equals(username)) {
                return true;
            }
        }
        return false;
    }

    public boolean isExistsEmail(String email) {
        ArrayList<User> list = iUserDao.findAllUser();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getEmail().equals(email)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void write() throws IOException {
        iUserDao.write();
    }

    @Override
    public void read() throws IOException, ClassNotFoundException {
        iUserDao.read();
    }

}
